/**
 * 
 */
package stc.skymobi.db;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

/**
 * @author hp
 *
 */
public class DbVOAppender {
	
    private static final Logger logger = LoggerFactory.getLogger(DbVOAppender.class);
    
    private	ExecutorService		exec = Executors.newSingleThreadExecutor();
    private SimpleJdbcTemplate  simpleJdbcTemplate;
    private	AtomicInteger		appendTaskCount = new AtomicInteger(0);
    
    /**
     * @param simpleJdbcTemplate the simpleJdbcTemplate to set
     */
    public void setSimpleJdbcTemplate(SimpleJdbcTemplate simpleJdbcTemplate) {
        this.simpleJdbcTemplate = simpleJdbcTemplate;
    }

    public void recordVO(final String updateSql, final List<Object[]> args) {
		if ( args.size() > 0 && null != updateSql ) {
			appendTaskCount.incrementAndGet();
			
			exec.submit(new Runnable(){

				public void run() {
					try {
						simpleJdbcTemplate.batchUpdate(updateSql, args );
					}
					catch (Exception e) {
						logger.error("batchUpdate JDBC Error:", e);
					}
					int count = appendTaskCount.decrementAndGet();
					if ( logger.isDebugEnabled() ) {
						logger.debug( "Pending Append Task Count : " + count );
					}
			}});
		}
		else {
			logger.error( "updateSql : " + updateSql + ", args size : " + args.size() ); 
		}
    }
    
    public void destroy() {
    	exec.shutdownNow();
    }
}
